package jdbc.three.service.proxy;

import jdbc.day2.demo4_对象工厂.ObjectFactory;
import jdbc.three.beans.Account;
import jdbc.three.exception.QueryMoneyEx;
import jdbc.three.exception.TransferEx;
import jdbc.three.service.AccountService;
import jdbc.three.transaction.TransactionManager;

import java.sql.SQLException;

public class AccountServiceProxy implements AccountService {
    AccountService t= (AccountService) ObjectFactory.getObject("accountServiceImpl");
    @Override
    public boolean register(Account a) throws SQLException {
        return t.register(a);
    }

    @Override
    public double queryMoney(int id) throws QueryMoneyEx {
        double rs= 0;
        try {
            rs = t.queryMoney(id);
        } catch (Exception e) {
            throw new QueryMoneyEx("查询失败");
        }
        if(rs<0){
            throw new QueryMoneyEx("查询钱出错");
        }
        return rs;
    }

    @Override
    public boolean transferMoney(int from, int to, double m) throws TransferEx ,SQLException{
        TransactionManager tm= (TransactionManager) ObjectFactory.getObject("transaction");
        tm.beginTransaction();
        try{
            t.transferMoney(from,to,m);
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw new TransferEx("转帐失败");
        }
        return true;
    }
}
